﻿#include "rgsfeatureaction.h"

#include<qgsvectorlayer.h>
#include<qgsvectorlayerutils.h>
#include<qgsattributedialog.h>

RgsFeatureAction::RgsFeatureAction(const QString &name, QgsFeature &f, QgsVectorLayer *layer,
                                   QUuid actionId, int defaultAttr, QObject *parent)
    :QAction( name, parent )
    , mLayer( layer )
    , mFeature( &f )
    , mActionId( actionId )
    , mIdx( defaultAttr )
    , mFeatureSaved( false )
{

}

bool RgsFeatureAction::addFeature(const QgsAttributeMap &defaultAttributes, bool showModal, QgsExpressionContextScope *scope, bool hideParent)
{
    if ( !mLayer || !mLayer->isEditable() )
        return false;

    const QgsFields fields = mLayer->fields();
    QgsAttributeMap initialAttributeValues;

    for ( int idx = 0; idx < fields.count(); ++idx )
    {
        if ( defaultAttributes.contains( idx ) )
        {
            initialAttributeValues.insert( idx, defaultAttributes.value( idx ) );
        }
    }


    QgsExpressionContext context = mLayer->createExpressionContext();
    if ( scope )
        context.appendScope( scope );

    const QgsFeature newFeature = QgsVectorLayerUtils::createFeature( mLayer, mFeature->geometry(), initialAttributeValues,
                                                                     &context );
    *mFeature = newFeature;

    bool isDisabledAttributeValuesDlg = true;

    if ( fields.count() == 0 )
        isDisabledAttributeValuesDlg = true;


    switch ( mLayer->editFormConfig().suppress() )
    {
    case QgsEditFormConfig::SuppressOn:
        isDisabledAttributeValuesDlg = true;
        break;
    case QgsEditFormConfig::SuppressOff:
        isDisabledAttributeValuesDlg = false;
        break;
    case QgsEditFormConfig::SuppressDefault:
        break;
    }


    if ( mForceSuppressFormPopup )
        isDisabledAttributeValuesDlg = true;

    if(isDisabledAttributeValuesDlg){
        mLayer->beginEditCommand( text() );
        mFeatureSaved = mLayer->addFeature( *mFeature );

        if ( mFeatureSaved )
        {
            mLayer->endEditCommand();
            mLayer->triggerRepaint();
        }
        else
        {
            mLayer->destroyEditCommand();
        }
        emit addFeatureFinished();
    }
    else {
        QgsAttributeDialog *dialog = newDialog( false );
        dialog->setAttribute( Qt::WA_DeleteOnClose );
        dialog->setMode( QgsAttributeEditorContext::AddFeatureMode );
        dialog->setEditCommandMessage( text() );

        if ( scope )
            dialog->setExtraContextScope( new QgsExpressionContextScope( *scope ) );

        connect( dialog->attributeForm(), &QgsAttributeForm::featureSaved, this, &RgsFeatureAction::onFeatureSaved );

        if ( !showModal )
        {
            setParent( dialog ); // keep dialog until the dialog is closed and destructed
            connect( dialog, &QgsAttributeDialog::finished, this, &RgsFeatureAction::addFeatureFinished );
            dialog->show();

            if ( hideParent )
            {
                connect( this, &RgsFeatureAction::addFeatureFinished, this, &RgsFeatureAction::unhideParentWidget );
                hideParentWidget();
            }
            mFeature = nullptr;
            return true;
        }

        dialog->exec();
        emit addFeatureFinished();
    }


    //临时
    return mFeatureSaved;
}

void RgsFeatureAction::hideParentWidget()
{
    QWidget *dialog = parentWidget();
    if ( dialog )
    {
        QWidget *triggerWidget = dialog->parentWidget();
        if ( triggerWidget && triggerWidget->window()->objectName() != QLatin1String( "RgisApp" ) )
            triggerWidget->window()->setVisible( false );
    }
}

void RgsFeatureAction::onFeatureSaved(const QgsFeature &feature)
{
    //??
    QgsAttributeForm *form = qobject_cast<QgsAttributeForm *>( sender() );

    Q_UNUSED( form ) // only used for Q_ASSERT
    Q_ASSERT( form );

    //??


    //又拷贝了一份
    if ( mFeature )
        *mFeature = feature;

    mFeatureSaved = true;


    //持久化存储值  -- 定义一个全局变量和配置文件

    //---


}

void RgsFeatureAction::unhideParentWidget()
{
    QWidget *dialog = parentWidget();
    if ( dialog )
    {
        QWidget *triggerWidget = dialog->parentWidget();
        if ( triggerWidget )
            triggerWidget->window()->setVisible( true );
    }
}

QgsAttributeDialog *RgsFeatureAction::newDialog(bool cloneFeature)
{
    QgsFeature *f = cloneFeature ? new QgsFeature( *mFeature ) : mFeature;
    QgsAttributeEditorContext context( Riskgis::instance()->createAttributeEditorContext() );


    QgsDistanceArea myDa;

    myDa.setSourceCrs( mLayer->crs(), QgsProject::instance()->transformContext() );
    myDa.setEllipsoid( QgsProject::instance()->ellipsoid() );

    context.setDistanceArea( myDa );
    context.setFormMode( QgsAttributeEditorContext::StandaloneDialog );

    QgsAttributeDialog *dialog = new QgsAttributeDialog( mLayer, f, cloneFeature, parentWidget(), true, context );

#ifndef Q_OS_WIN
    dialog->setWindowFlags( dialog->windowFlags() | Qt::Tool );
#else
    dialog->setWindowFlags( dialog->windowFlags() | Qt::CustomizeWindowHint | Qt::WindowMaximizeButtonHint );
    if ( ! dialog->parent() )
        dialog->setWindowFlag( Qt::WindowStaysOnTopHint );
#endif

    dialog->setObjectName( QStringLiteral( "featureactiondlg:%1:%2" ).arg( mLayer->id() ).arg( f->id() ) );



    //临时
    return dialog;

}
